<template>
  <div>
    <div class="input">
      <van-field readonly clickable label="测试数据" :value="selectData.text" placeholder="选择测试数据..." @click="selectingData = true"></van-field>
      <van-popup v-model="selectingData" round position="bottom">
        <van-picker title="测试数据" show-toolbar :columns="dataColumn" @cancel="selectingData = false" @confirm="dataSelected"></van-picker>
      </van-popup>
      <div class="test-data-container">
        <canvas id="test-data"></canvas>
      </div>
    </div>
    <van-divider v-if="hasResult">
    </van-divider>
    <div v-if="hasResult" class="result-wrapper">
      <div class="result">
        <div>
          <p>未来七天趋势</p>
        </div>
        <div v-if="done">
          <p>网络耗时：{{ totalTime - calcTime }}ms</p>
          <p>计算耗时：{{ calcTime}}ms</p>
        </div>
      </div>
      <div v-if="error" class="error">
        <div>
          <img src="imgs/error.png" />
          <p>无法识别</p>
        </div>
      </div>
      <div v-show="!error" class="result-data-container">
        <canvas id="result-data"></canvas>
      </div>
    </div>
    <div class="btn-container">
      <van-button :disabled="!hasInput" type="primary" @click="save">{{ btnText }}</van-button>
    </div>
  </div>
</template>

<script lang="ts">

import Component from 'vue-class-component'
import Vue from 'vue'
import { apiAxios } from '@/api/axios'
import F2 from '@antv/f2/lib/index-all'

@Component
export default class ShuangTan30 extends Vue {
  hasResult = false
  totalTime = 0
  error = false
  noResult = false
  hasInput = false
  testDataChart? : F2.Chart
  resultDataChart? : F2.Chart

  selectData = { text: '', id: '' }

  selectingData = false
  dataColumn : any[] = []
  testData : any = {}

  calcTime = 0
  done = false

  get btnText () : string {
    return this.done ? '重新计算' : '计算'
  }

  dataSelected (value : any) {
    this.selectData = value
    this.selectingData = false
    this.hasInput = this.selectData.id !== ''
    if (this.selectData.id) {
      apiAxios.get(`/open/test/data/${this.selectData.id}`).then((res: any) => {
        this.testData = {
          zOAVelocity: res.zOAVelocity,
          rmse: res.rmse
        }
        if (this.testDataChart) {
          this.testDataChart.destroy()
        }
        const data :any[] = []
        for (let i = 0; i < this.testData.zOAVelocity.length; i++) {
          data.push({ idx: i + 1, type: 'zOAVelocity', value: this.testData.zOAVelocity[i].data })
          data.push({ idx: i + 1, type: 'rmse', value: this.testData.rmse[i].data })
        }
        this.testDataChart = new F2.Chart({
          id: 'test-data',
          pixelRatio: window.devicePixelRatio
        })
        this.testDataChart.source(data, {
          idx: {
            min: 1,
            max: 100
          }
        })

        this.testDataChart.line().position('idx*value').color('type')
        this.testDataChart.interaction('pan')

        this.testDataChart.render()
      })
    }
  }

  async created () {
    this.dataColumn = await apiAxios.get('/open/test/data/phm_seqs')
    this.$store.state.var.algoId = 'aiConstruct_9'
    this.$store.state.var.title = '设备寿命预测'
  }

  async save () {
    const startTime = Date.now()
    try {
      this.hasResult = true
      this.error = false
      this.noResult = false
      this.done = false
      let resp: any = await apiAxios.post('/device/phm/predict', this.testData)
      this.calcTime = parseInt(resp.headers['x-calc-cost-metric'])
      this.done = true
      this.totalTime = Date.now() - startTime
      // Hijack, 提供mock数据
      if (resp.code !== 0) {
        resp = {
          code: 0,
          message: '',
          data: {
            rmse: [
              0.6122311594989323,
              0.6532347854716839,
              0.6739763730447209,
              0.6937246117977881,
              0.801912512833817,
              0.40703835629136353,
              0.7235617738254153
            ],
            zOAVelocity: [
              0.11447819946058185,
              0.11339297389611049,
              0.11546688761159074,
              0.11960961782050694,
              0.11116889356961522,
              0.12119545136411904,
              0.12108476428709584
            ]
          },
          ts: 1639583412318,
          trace: ''
        }
      }
      const code = (resp as any).code
      if (code !== 0) {
        this.error = true
      } else {
        if (this.resultDataChart) {
          this.resultDataChart.destroy()
        }
        const data :any[] = []
        for (let i = 0; i < resp.data.zOAVelocity.length; i++) {
          data.push({ idx: i + 1, type: 'zOAVelocity', value: resp.data.zOAVelocity[i] })
          data.push({ idx: i + 1, type: 'rmse', value: resp.data.rmse[i] })
        }
        this.$nextTick(() => {
          this.resultDataChart = new F2.Chart({
            id: 'result-data',
            pixelRatio: window.devicePixelRatio
          })
          this.resultDataChart.source(data)
          this.resultDataChart.axis('idx', {
            label: function () {
              return ''
            }
          })
          this.resultDataChart.line().position('idx*value').color('type')
          this.resultDataChart.render()
        })
      }
    } catch (e) {
      this.error = true
      console.log(e)
    }
    this.hasResult = true
  }
}
</script>

<style lang="less" scoped>
.btn-container {
  padding: 1.25rem;
}
.test-data-container {
  padding: 1rem;
  height: 15rem;
  display: block;
  position: relative;
  user-select: none;
  #test-data {
    width: 100%;
    height: 100%;
    display: block;
    -webkit-user-drag: none;
  }
}
.result-data-container {
  padding: 1rem;
  height: 15rem;
  display: block;
  position: relative;
  user-select: none;
  #result-data {
    width: 100%;
    height: 100%;
    display: block;
  }
}
.result-wrapper {
  min-height: 21rem;
  padding: 1.25rem;
  .result {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-family: PingFangSC-Regular;
    margin-bottom: 1.25rem;
    & > div:first-child {
      font-size: 1.25rem;
      color: #323333;
    }
    & > div:last-child {
      font-size: 0.88rem;
      color: #929292;
    }
  }
  .secondary {
    font-size: 0.88rem;
    color: #929292;
  }
  .error {
    min-height: 14.8rem;
    display: table;
    margin: 0 auto;
    & > div {
      display: table-cell;
      vertical-align: middle;
      text-align: center;
    }
    img {
      width: 5rem;
      height: 5rem;
    }
    p {
      font-size: 1.25rem;
      color: #323333;
      margin-top: 1.25rem;
    }
  }
}
</style>
